package com.chief.sink.elasticsearch;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.CreateOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexRequest;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.util.ObjectBuilder;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class EsDataPrepare {

    static JacksonJsonpMapper jacksonJsonpMapper = new JacksonJsonpMapper();//json映射器

    static RestClient restClient = RestClient.builder(
            new HttpHost("hadoop52", 9200),
            new HttpHost("hadoop53", 9200),
            new HttpHost("hadoop54", 9200),
            new HttpHost("hadoop55", 9200)
    ).build();
    static  ElasticsearchTransport  transport = new RestClientTransport(restClient, jacksonJsonpMapper);
    static ElasticsearchClient  client = new ElasticsearchClient(transport);

    @Test
    public void sss() throws IOException {
        SearchResponse<JSONObject> searchResponse = client.search(new SearchRequest.Builder().index("products").build(), JSONObject.class);
        List<Hit<JSONObject>> list2 = searchResponse.hits().hits();
        for (Hit<JSONObject> hit : list2) {
            System.out.println(hit.source().toJSONString());
        }
    }

    @Test
    public void Test() throws Exception {
        BooleanResponse exists = client.indices().exists(e -> e.index("aaaaaaaaaaaaa"));
        System.out.println(exists.value());
    }

    public static void main(String[] args) throws Exception {

        DeleteIndexResponse products2 = client.indices().delete(new DeleteIndexRequest.Builder().index("products").build());
        System.out.println("删除索引：products:" + products2.acknowledged());

        Thread.sleep(10000);

        CreateIndexResponse products1 = client.indices().create(new CreateIndexRequest.Builder().index("products").build());
//        client.indices().create(c->c.index(""));
        System.out.println("创建索引测试：products:" + products1.acknowledged());

        Thread.sleep(10000);

        Map<String, String> map = new HashMap<>();
        map.put("name", "product 0");
        map.put("price", String.valueOf(50 + (int) (Math.random() * 500)));
        CreateRequest products = new CreateRequest.Builder().document(map)
                .id("0").index("products").build();
        CreateResponse createResponse = client.create(products);
        System.out.println("创建单个文档测试:" + createResponse.result().jsonValue());


        List<BulkOperation> list = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            map = new HashMap<>();
            map.put("name", "product " + i);
            map.put("price", String.valueOf(50 + (int) (Math.random() * 500)));
            list.add(new BulkOperation.Builder().create(
                    new CreateOperation.Builder<Map>().id("" + i)
                            .document(map).index("products")
                            .build()
            ).build());
        }
        BulkResponse bulkResponse = client.bulk(new BulkRequest.Builder().operations(list).build());
        System.out.println("创建批量文档测试:" + bulkResponse.items().get(0).result());

        Thread.sleep(10000);

        SearchResponse<JSONObject> searchResponse = client.search(new SearchRequest.Builder().index("products").build(), JSONObject.class);
        List<Hit<JSONObject>> list2 = searchResponse.hits().hits();
        List<Object> result = new ArrayList<>();
        for (Hit<JSONObject> hit : list2) {
            result.add(hit.source());
        }
        System.out.println("SearchRequest all:" + result);


        SearchRequest searchRequest = new SearchRequest.Builder()
                .index("products").query(new Query.Builder().range(RangeQuery.of(new Function<RangeQuery.Builder, ObjectBuilder<RangeQuery>>() {
                    @Override
                    public ObjectBuilder<RangeQuery> apply(RangeQuery.Builder builder) {
                        return builder.field("price").gte(JsonData.of("300")).lte(JsonData.of("500"));
                    }
                })).build())
                .build();
        SearchResponse<Object> search = client.search(searchRequest, Object.class);
        for (Hit<Object> hit : search.hits().hits()) {
            System.out.println(hit.source());
        }

        System.out.println("===================");

        SearchResponse<Object> searchResponse3 =
                client.search(
                        s -> s.index("products").query(
                                c -> c.bool(
                                        b -> b.filter(
                                                q -> q.range(
                                                        v -> v.field("price").gte(JsonData.of("300")).lte(JsonData.of("500"))))))
                        , Object.class);
        List<Hit<Object>> list3 = searchResponse3.hits().hits();
        List<Object> result3 = new ArrayList<>();
        for (Hit<Object> hit : list3) {
            result3.add(hit.source());
        }
        System.out.println("SearchRequest range:" + result);


        DeleteResponse deleteResponse = client.delete(new DeleteRequest.Builder().index("products").id("3").build());
        System.out.println("deleteResponse range:" + deleteResponse.result());

    }
}
